package com.cj.core.annotation.log.context;

/**
 * 日志收集线程池
 * */
public class CustomLogContext {
    private static final ThreadLocal<StringBuilder> logBuffer = ThreadLocal.withInitial(StringBuilder::new);
    private static final ThreadLocal<Boolean> inStructuredLog = ThreadLocal.withInitial(() -> false);

    public static void start() {
        inStructuredLog.set(true);
    }

    public static void stop() {
        inStructuredLog.remove();
        logBuffer.get().setLength(0);
        logBuffer.remove();
    }

    public static boolean isCollecting() {
        return Boolean.TRUE.equals(inStructuredLog.get());
    }

    public static void add(String message) {
        if (isCollecting()) {
            logBuffer.get().append(message).append(System.lineSeparator());
        }
    }

    public static String getAndClear() {
        StringBuilder sb = logBuffer.get();
        String content = sb.toString();
        sb.setLength(0);
        return content;
    }
}
